import { defineStore } from 'pinia'
import { getTasks, addTask, updateTask, deleteTask, runTask } from '@/api/task'
import { useToastStore } from './toast'

function normalizeTask(t) {
  return {
    id: t.id ?? t.ID ?? null,
    name: t.name ?? t.Name ?? '',
    status: t.status ?? t.Status ?? 'stopped',
    count: t.count ?? t.Count ?? 0,
    yaml: t.yaml ?? t.YAML ?? t.template ?? ''
  }
}

export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [],
    loadingMap: {}
  }),
  getters: {
    isLoading: (state) => (id) => !!state.loadingMap[id]
  },
  actions: {
    async getAllTasks() {
      const toast = useToastStore()
      try {
        const res = await getTasks()
        this.tasks = (res || []).map(normalizeTask)
        return this.tasks
      } catch (err) {
        toast.showToast('获取任务列表失败', 'danger')
        throw err
      }
    },
    async createTask(taskData) {
      const toast = useToastStore()
      try {
        const res = await addTask(taskData)
        const newTask = normalizeTask(res?.data ?? res)
        this.tasks.push(newTask)
        toast.showToast('任务创建成功', 'success')
        return newTask
      } catch (err) {
        toast.showToast('任务创建失败', 'danger')
        throw err
      }
    },
    async modifyTask(id, taskData) {
      const toast = useToastStore()
      try {
        const res = await updateTask(id, taskData)
        const updated = normalizeTask(res?.data ?? res ?? taskData)
        const idx = this.tasks.findIndex(t => t.id === id)
        if (idx !== -1) this.tasks[idx] = { ...this.tasks[idx], ...updated }
        toast.showToast('任务更新成功', 'success')
        return updated
      } catch (err) {
        toast.showToast('任务更新失败', 'danger')
        throw err
      }
    },
    async removeTask(id) {
      const toast = useToastStore()
      try {
        await deleteTask(id)
        this.tasks = this.tasks.filter(t => t.id !== id)
        toast.showToast('任务删除成功', 'success')
      } catch (err) {
        toast.showToast('任务删除失败', 'danger')
        throw err
      }
    },
    async runTaskNow(taskOrId) {
      const toast = useToastStore()
      const id = typeof taskOrId === 'object' ? taskOrId.id : taskOrId
      if (!id || this.loadingMap[id]) return
      this.loadingMap[id] = true
      try {
        const res = await runTask(id)
        const payload = res?.data ?? res ?? {}
        const t = this.tasks.find(x => x.id === id)
        if (t) {
          t.status = payload.status ?? t.status
          t.count = payload.count ?? t.count
        }
        toast.showToast('任务已启动', 'info')
        return payload
      } catch (err) {
        toast.showToast('任务启动失败', 'danger')
        throw err
      } finally {
        this.loadingMap[id] = false
      }
    }
  }
})
